#include "mysql_session.h"

#include "chat_session_member-odb.hxx"
#include "log.h"

namespace chat {
bool ChatSessionMemberTable::append(ChatSessionMember& session_member) {
    try {
        // 获取事务对象开启事务
        odb::transaction trans(db_->begin());

        db_->persist(session_member);

        // 提交事务
        trans.commit();

    } catch (const std::exception& e) {
        LOG_ERROR("新增session_member[{}-{}]失败: {}", session_member.user_id(),
                  session_member.session_id(), e.what());

        return false;
    }

    return true;
}
bool ChatSessionMemberTable::append(
    std::vector<ChatSessionMember>& session_members) {
    try {
        // 获取事务对象开启事务
        odb::transaction trans(db_->begin());
        for (auto& session_member : session_members) {
            db_->persist(session_member);
        }

        // 提交事务
        trans.commit();

    } catch (const std::exception& e) {
        LOG_ERROR("新增session_members(size = {})失败: {}",
                  session_members.size(), e.what());

        return false;
    }

    return true;
}
bool ChatSessionMemberTable::remove(const ChatSessionMember& session_member) {
    try {
        // 获取事务对象开启事务
        odb::transaction trans(db_->begin());

        db_->erase_query<ChatSessionMember>(
            odb::query<ChatSessionMember>::user_id ==
                session_member.user_id() &&
            odb::query<ChatSessionMember>::session_id ==
                session_member.session_id());

        trans.commit();

    } catch (const std::exception& e) {
        LOG_ERROR("删除单个session member[{}-{}]失败: {}",
                  session_member.user_id(), session_member.session_id(),
                  e.what());

        return false;
    }

    return true;
}
bool ChatSessionMemberTable::remove(const std::string& session_id) {
    try {
        // 获取事务对象开启事务
        odb::transaction trans(db_->begin());

        db_->erase_query<ChatSessionMember>(
            odb::query<ChatSessionMember>::session_id == session_id);

        trans.commit();

    } catch (const std::exception& e) {
        LOG_ERROR("删除会话[{}]失败: {}", session_id, e.what());

        return false;
    }

    return true;
}
std::vector<std::string> ChatSessionMemberTable::members(
    const std::string& session_id) {
    std::vector<std::string> res;

    try {
        // 获取事务对象开启事务
        odb::transaction trans(db_->begin());

        odb::result<ChatSessionMember> r(db_->query<ChatSessionMember>(
            odb::query<ChatSessionMember>::session_id == session_id));

        for (auto& user : r) {
            res.push_back(user.user_id());
        }

        trans.commit();

    } catch (const std::exception& e) {
        LOG_ERROR("根据session_id[{}]获取所有user失败: {}", session_id,
                  e.what());

        return res;
    }

    return res;
}
}  // namespace chat